package dsf.eshop.commons.base;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import org.springframework.data.redis.serializer.SerializationException;

import java.nio.charset.Charset;

public abstract class BaseRedisSerializerImpl<T> implements BaseRedisSerializer<T> {

    private Class<T> tClass;

    public BaseRedisSerializerImpl(Class<T> tClass) {
        this.tClass = tClass;
    }

    @Override
    public byte[] serialize(T t) throws SerializationException {

        if(null == t) {
            return new byte[0];
        }
        return JSON.toJSONString(t, SerializerFeature.WriteClassName).getBytes(Charset.defaultCharset());
    }

    @Override
    public T deserialize(byte[] bytes) throws SerializationException {

        T t = null;
        if(bytes == null || bytes.length <= 0) {
            return t;
        }
        t = (T) JSON.parseObject(bytes, tClass);
        return t;
    }
}
